package com.example.lanouhn.firstapp.activity.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.model.Goods;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * 首页界面的最新商品的数据适配器
 */
public class GoodsRecommendAdapter extends RecyclerView.Adapter {

    //上下文对象
    private Context context;
    //数据集合
    private List<Goods> list;


    //设置recycle的监听事件接口

    /**
     * 定义接口里面实现点击事件方法
     */
    public interface GoodsRecommendRecyclerViewListener{
        void onclick(View view,int postion);
    }
    //定义GoodsRecommendRecyviewListent变量
    private GoodsRecommendRecyclerViewListener goodsRecommendRecyviewListent;
    //注册事件
    public void setGoodsRecommendRecyviewListent(GoodsRecommendRecyclerViewListener
                   goodsRecommendRecyviewListent){
        this.goodsRecommendRecyviewListent = goodsRecommendRecyviewListent;
    }

    public GoodsRecommendAdapter(List<Goods> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //加载布局
        RecyclerView.ViewHolder holder = null;

        holder = new VHolder(
                LayoutInflater.from(context).

                        inflate(R.layout.homepage_item_list,null));

        return holder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        final VHolder vHolder = (VHolder) holder;
        //数据位置
        Goods goods = list.get(position);
        //设置数据 运用picasso获取图片
        Picasso.with(context).load(goods.getGoods_image_url()).into(vHolder.imageView);
        vHolder.tv_name.setText(goods.getGoods_name());
        vHolder.tv_price.setText(goods.getGoods_price());


        //item的点击事件
        vHolder.itemView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {

                goodsRecommendRecyviewListent.onclick(vHolder.itemView,position);
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    //定义VHolder类继承RecyclerView.ViewHolder
    class VHolder extends RecyclerView.ViewHolder{

        private ImageView imageView;
        private TextView tv_name;
        private TextView tv_price;
        //绑定控件id
        public VHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.imageview);
            tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            tv_price = (TextView) itemView.findViewById(R.id.tv_price);


        }
    }


}
